module.exports = app => {
  const express = require("express")
  const auth = require("../../middleware/auth")

  const router = express.Router({
    mergeParams: true
  })

  router.get('/info', async (req, res) => {
    //教师查看自己个人信息接口
    let queryOptions = {}
    queryOptions.populate = [{
      path: 'department',
      select: ['name', 'nid'],
      populate: {
        path: 'superior',
        select: ['name', 'nid']
      }
    }]
    const Teacher = require("../../models/Teacher")
    let model = await Teacher.findById(req.user.bindId).setOptions(queryOptions);
    res.send(model)
  })
  //教师修改自己个人信息接口
  router.put('/info', async (req, res) => {
    const Teacher = require("../../models/Teacher")
    let model = await Teacher.findByIdAndUpdate(req.user.bindId, req.body)
    if (model) {
      res.send({
        success: true,
        message: '修改成功！'
      })
    } else {
      res.send({
        success: false,
        message: '修改失败！'
      })
    }
  })
  //获取自己的用户信息
  router.get("/userInfo", async (req, res) => {
    const User = require('../../models/User')
    let model = await User.findById(req.user._id, {
      "username": 1
    })
    res.send(model)
  })
  //更改密码
  router.put('/password', async (req, res) => {
    const User = require("../../models/User")
    let model = await User.findByIdAndUpdate(req.user._id, req.body)
    if (model) {
      res.send({
        success: true,
        message: '修改成功！'
      })
    } else {
      res.send({
        success: false,
        message: '修改失败！'
      })
    }
  })
  //获取这时候的学期
  router.get("/nowXnAndXq", async (req, res) => {
    // console.log();
    const date = new Date()
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let xq = 1;
    if (month >= 2 && month < 9) {
      xq = 2
      year = (year - 1) + '-' + year
    }
    if (month >= 9 && month <= 12) {
      xq = 1;
      year = year + '-' + (year + 1)
    }
    if (month == 1) {
      xq = 1;
      year = (year - 1) + '-' + year
    }
    // console.log(year);
    res.send({
      xn: year,
      xq: xq
    })

  })
  //获取课表
  router.get('/schedule', async (req, res) => {
    //1.首先，先拿到对应的老师的id
    let id = req.user.bindId;
    const {
      xn,
      xq
    } = req.query;
    //请求过来的东西里面有时间和地点
    const Course = require('../../models/Course')
    let courseList = await Course.find({
      teacher: id,
      year: xn,
      xq
    }, {
      coursename: 1,
      time: 1,
      address: 1
    })

    for (var i = 0; i < courseList.length; i++) {
      for (var j = i + 1; j < courseList.length; j++) {
        if (courseList[i].coursename == courseList[j].coursename && courseList[i].time == courseList[j].time && courseList[i].address == courseList[j].address) { //第一个等同于第二个，splice方法删除第二个
          courseList.splice(j, 1);
          j--;
        }
      }
    }
    res.send(courseList)
    //2.然后去课程上面找有他id，学年和学期是前端传过来的值的所有课程
    //数据怎么处理，首先，我们只取课程名字，然后去重，然后根据课程名字，学期，学年，任课老师，得到所有的时间，和对应的地点
    //然后根据时间，一个个放进数组里面，然后给前端，然后展示就好了
    //3.然后进行课程的去重，将重复的合并在一起

    //4.将数据整合成前端需要的类型，然后发送
  })

  //这里获取班级列表，多级联动中
  router.post('/getClassList', async (req, res) => {
    const Course = require('../../models/Course')
    let {
      xn,
      xq
    } = req.body;
    let teacher = req.user.bindId;
    let classList = await Course.find({
      year: xn,
      xq,
      teacher
    }, {
      class: 1
    }).populate('class');

    for (let i = 0; i < classList.length; i++) {
      for (let j = i + 1; j < classList.length; j++) {
        if (classList[i].class.name == classList[j].class.name) { //第一个等同于第二个，splice方法删除第二个
          classList.splice(j, 1);
          j--;
        }
      }
    }
    res.send(classList)
  })

  //根据班级ID，学期，学年，教师id找到课程，返回
  router.post('/classIdToGetSchedule', async (req, res) => {
    const Course = require("../../models/Course")
    let teacher = req.user.bindId;
    const {
      xq,
      xn
    } = req.body
    let classId = req.body.class
    let scheduleList = await Course.find({
      year: xn,
      xq,
      teacher,
      class: classId
    }, {
      coursename: 1
    })
    res.send(scheduleList)
  })
  //获取要打分的成绩
  router.get('/getGradeList/:classId/:courseId', async (req, res) => {
    const Grade = require("../../models/Grade")
    const queryOptions = {}
    queryOptions.populate = [{
        "path": 'student',
        select: ['nid', 'name']
      },
      {
        "path": 'course',
        select: ['coursename', 'zxf', 'zjd']
      }
    ]
    let gradeList = await Grade.find({
      course: req.params.courseId
    }).setOptions(queryOptions)

    let sortGradeList = gradeList.sort(function (a, b) {
      return a.student.nid - b.student.nid
    })
    res.send(sortGradeList)
  })
  //给学生打分
  router.post('/changeStudentGrade', async (req, res) => {
    const {
      list,
      zxf,
      zjd
    } = req.body,
      result = [],
      Grade = require("../../models/Grade")
    list.forEach(value => {
      value.gpa = ((value.grade / 100) * zjd).toFixed(2)
      value.xf = zxf
    });

    for (let i = 0; i < list.length; i++) {
      let res = await Grade.findByIdAndUpdate(list[i]._id, {
        grade: list[i].grade,
        gpa: list[i].gpa,
        xf:list[i].xf,
        isEdit: true
      })
      if (res) {
        result.push(res)
      }
    }
    if (result.length == list.length) {
      res.send({
        success: true,
        message: '提交成功！'
      })
    } else {
      res.send({
        success: false,
        message: '提交失败'
      })
    }

  })
  
  app.use('/admin/api/teacherPageAPI', auth(), router)
}